import React, { Component } from 'react';
import { connect } from 'dva';
import { formatMessage, FormattedMessage } from 'umi/locale';
import Link from 'umi/link';
import router from 'umi/router';
import { Form, Input, Button, Select, Row, Col, Popover, Progress,Icon,message } from 'antd';
import styles from './Register.less';
import loginImg from '../../assets/r.png';
const FormItem = Form.Item;
const { Option } = Select;
const InputGroup = Input.Group;
const HeartSvg = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="26.001" height="26" viewBox="0 0 26.001 26">

    <g transform="translate(-72.209 -75.924)">
      <path fill="#999999" d="M-10037.187-2771.435a12.959,12.959,0,0,1-4.133-2.786,12.989,12.989,0,0,1-2.787-4.132,12.954,12.954,0,0,1-1.021-5.061,12.952,12.952,0,0,1,1.021-5.059,12.986,12.986,0,0,1,2.787-4.132,12.959,12.959,0,0,1,4.133-2.786,12.925,12.925,0,0,1,5.061-1.022,12.929,12.929,0,0,1,5.059,1.022,12.965,12.965,0,0,1,4.132,2.786,12.951,12.951,0,0,1,2.786,4.132,12.918,12.918,0,0,1,1.022,5.059,12.92,12.92,0,0,1-1.022,5.061,12.954,12.954,0,0,1-2.786,4.132,12.965,12.965,0,0,1-4.132,2.786,12.929,12.929,0,0,1-5.059,1.022A12.925,12.925,0,0,1-10037.187-2771.435Zm-6.73-11.979a11.8,11.8,0,0,0,11.791,11.791,11.8,11.8,0,0,0,11.789-11.791,11.8,11.8,0,0,0-11.789-11.789A11.8,11.8,0,0,0-10043.918-2783.414Zm11.911,3.24a7.451,7.451,0,0,0-6.88,4.566l-1.115-.47a8.674,8.674,0,0,1,3.141-3.821,8.655,8.655,0,0,1,2.116-1.043,5.661,5.661,0,0,1-2.921-4.952,5.665,5.665,0,0,1,5.658-5.66,5.666,5.666,0,0,1,5.66,5.66,5.665,5.665,0,0,1-2.922,4.952,8.657,8.657,0,0,1,2.115,1.043,8.685,8.685,0,0,1,3.143,3.821l-1.115.47A7.452,7.452,0,0,0-10032.007-2780.174Zm-4.45-5.72a4.453,4.453,0,0,0,4.449,4.449,4.455,4.455,0,0,0,4.45-4.449,4.455,4.455,0,0,0-4.45-4.45A4.454,4.454,0,0,0-10036.457-2785.894Z" transform="translate(10117.338 2872.337)" />
    </g>
  </svg>
);
const HeartSvg1 = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="26.001" height="26" viewBox="0 0 26.001 26">

    <g transform="translate(-72.209 -75.924)">
      <path fill="#000" d="M-10037.187-2771.435a12.959,12.959,0,0,1-4.133-2.786,12.989,12.989,0,0,1-2.787-4.132,12.954,12.954,0,0,1-1.021-5.061,12.952,12.952,0,0,1,1.021-5.059,12.986,12.986,0,0,1,2.787-4.132,12.959,12.959,0,0,1,4.133-2.786,12.925,12.925,0,0,1,5.061-1.022,12.929,12.929,0,0,1,5.059,1.022,12.965,12.965,0,0,1,4.132,2.786,12.951,12.951,0,0,1,2.786,4.132,12.918,12.918,0,0,1,1.022,5.059,12.92,12.92,0,0,1-1.022,5.061,12.954,12.954,0,0,1-2.786,4.132,12.965,12.965,0,0,1-4.132,2.786,12.929,12.929,0,0,1-5.059,1.022A12.925,12.925,0,0,1-10037.187-2771.435Zm-6.73-11.979a11.8,11.8,0,0,0,11.791,11.791,11.8,11.8,0,0,0,11.789-11.791,11.8,11.8,0,0,0-11.789-11.789A11.8,11.8,0,0,0-10043.918-2783.414Zm11.911,3.24a7.451,7.451,0,0,0-6.88,4.566l-1.115-.47a8.674,8.674,0,0,1,3.141-3.821,8.655,8.655,0,0,1,2.116-1.043,5.661,5.661,0,0,1-2.921-4.952,5.665,5.665,0,0,1,5.658-5.66,5.666,5.666,0,0,1,5.66,5.66,5.665,5.665,0,0,1-2.922,4.952,8.657,8.657,0,0,1,2.115,1.043,8.685,8.685,0,0,1,3.143,3.821l-1.115.47A7.452,7.452,0,0,0-10032.007-2780.174Zm-4.45-5.72a4.453,4.453,0,0,0,4.449,4.449,4.455,4.455,0,0,0,4.45-4.449,4.455,4.455,0,0,0-4.45-4.45A4.454,4.454,0,0,0-10036.457-2785.894Z" transform="translate(10117.338 2872.337)" />
    </g>
  </svg>
);
const HeartIcon = props => <Icon component={HeartSvg} {...props} />;
const HeartIcon1 = props => <Icon component={HeartSvg1} {...props} />;
const passwordStatusMap = {
  ok: (
    <div className={styles.success}>
      <FormattedMessage id="validation.password.strength.strong" />
    </div>
  ),
  pass: (
    <div className={styles.warning}>
      <FormattedMessage id="validation.password.strength.medium" />
    </div>
  ),
  poor: (
    <div className={styles.error}>
      <FormattedMessage id="validation.password.strength.short" />
    </div>
  ),
};

const passwordProgressMap = {
  ok: 'success',
  pass: 'normal',
  poor: 'exception',
};

@connect(({ loading }) => ({
  submitting: loading.effects['auth/register'],
}))
@Form.create()
class Register extends Component {
  state = {
    count: 0,
    confirmDirty: false,
    visible: false,
    help: '',
    prefix: '86',
    checkName:"",
    checkCName:"",
    phoneNum:"",
    newPassword:"",
    returnPassword:"",
    validateId:"",
    messageCode:""
  };

  componentWillUnmount() {
    clearInterval(this.interval);
  }

  onGetCaptcha = () => {
    
    if(this.state.checkName==""){
      message.error("请选择账号后发送验证码", 3);
      return
    }
    
    const { dispatch, history } = this.props;
      dispatch({
        type: 'auth/postCode',
        payload: {
          data: {
            "channel": "02",
            "mobile": this.state.phoneNum,
            "username":this.state.checkName
          }
        },
        callback: (res) => {
          console.log("res........",res);  
          if(res.code ==200){
            let count = 59;
            this.setState({ count });
            this.interval = setInterval(() => {
              count -= 1;
              this.setState({ count });
              if (count === 0) {
                clearInterval(this.interval);
              }
            }, 1000);
            this.setState({
              validateId:res.data.validateId
            })
          }
          else{
            message.error(res.code, 3);
          }
          
          // if(res.code != 200){
          //   message.error(res.msg, 3);
          //   return false;
          // }
          // history.push('/info/account')     // created by xiong
        }
      })
  };

  getPasswordStatus = () => {
    const { form } = this.props;
    const value = form.getFieldValue('password');
    if (value && value.length > 9) {
      return 'ok';
    }
    if (value && value.length > 5) {
      return 'pass';
    }
    return 'poor';
  };

  handleSubmit = e => {
    e.preventDefault();
    const { form, dispatch,history } = this.props;
    console.log(form)
    form.validateFields({ force: true }, (err, values) => {
      console.log(err)
      if (!err) {
        console.log(err)
        dispatch({
          type: 'auth/register',
          payload: {
            data: {
              "channel": 5,
              "handPhone": this.state.phoneNum,
              "validateId":this.state.validateId,
              "messageCode":this.state.messageCode,
              "newPassword1":this.state.newPassword,
              "newPassword2":this.state.returnPassword,
              "username":this.state.checkName
            }
          },
          callback: (res) => {
            console.log("res+++++",res);  
            if(res.code == 200){
              message.success("修改成功", 3);
              history.push('/auth/login')
            }
            else{
              message.error(res.msg, 3);
            }
           
          }
        });
      }
    });
  };

  handleConfirmBlur = e => {
    const { value } = e.target;
    const { confirmDirty } = this.state;
    this.setState({ confirmDirty: confirmDirty || !!value });
  };

  checkConfirm = (rule, value, callback) => {
    const { form } = this.props;
    console.log(value)
    this.setState({
      returnPassword:value
    })
    if (value && value !== form.getFieldValue('password')) {
      callback(formatMessage({ id: 'validation.password.twice' }));
    } else {
      callback();
    }
  };

  checkPassword = (rule, value, callback) => {
    const { visible, confirmDirty } = this.state;
  
    this.setState({
      newPassword:value
    })
    
      
      if (value.length < 6) {
        console.log("++++,",value.length)
        callback(formatMessage({ id: 'validation.password.strength.msg' }));
      } else {
        const { form } = this.props;
        if (value && confirmDirty) {
          form.validateFields(['confirm'], { force: true });
        }
        callback();
      }
    
  };

  changePrefix = value => {
    this.setState({
      prefix: value,
    });
  };

  renderPasswordProgress = () => {
    const { form } = this.props;
    const value = form.getFieldValue('password');
    const passwordStatus = this.getPasswordStatus();
    return value && value.length ? (
      <div className={styles[`progress-${passwordStatus}`]}>
        <Progress
          status={passwordProgressMap[passwordStatus]}
          className={styles.progress}
          strokeWidth={6}
          percent={value.length * 10 > 100 ? 100 : value.length * 10}
          showInfo={false}
        />
      </div>
    ) : null;
  };
  getCode=(e)=>{
    console.log(e.target.value)
    this.setState({
      messageCode:e.target.value
    })
  }
  getData = (e) => {
    console.log(e)
    console.log(e.target.value)
    if(e.target.value !="" && !this.state.autoFlag){
      this.setState({
        autoFlag:true
      })
      return
    }
    this.setState({
      checkName:"",
      checkCName:"",
      phoneNum:""
    })
    const { dispatch } = this.props;
    const reg = /^\d{11}$/;
    if (reg.test(e.target.value)) {
      this.setState({
        phoneNum:e.target.value
      })
      dispatch({
        type: 'auth/SelectUserInfo',
        payload: {
          data: { "mobile": e.target.value }
        },
        callback: (res) => {
          console.log("res", res);// 请求完成后返回的结果
          if(res.code != 200){
            message.error(res.msg, 3);
            return false;
          }
          if (res) {

            this.setState({
              getDataList: res.data,
              phoneNum:this.state.phoneNum
            })
          }
        }
      });
    }
    else{
      this.setState({
        getDataList:""
      })
    }


  }
  checkUsername(u,p) {
    console.log(u+""+p)
    this.setState({
      checkName:u,
      checkCName:p
    })
  }
  reset(){
    this.setState({
      checkName:"",
      checkCName:""
    })
  }
  render() {
    const { form, submitting } = this.props;
    const { getFieldDecorator } = form;
    const { count, prefix, help, visible } = this.state;
    return (
      <div className={styles.main}>
        <h3>
          <img src={loginImg}  style={{width:160}}/>
        </h3>
        <Form onSubmit={this.handleSubmit}>
        <FormItem>
            <InputGroup compact>
              {/* <Select
                size="large"
                value={prefix}
                onChange={this.changePrefix}
                style={{ width: '25%' }}
              >
                <Option value="86">+86</Option>
              </Select> */}
              {getFieldDecorator('mobilephone', {
                rules: [
                  {
                    required: true,
                    message: formatMessage({ id: 'validation.phone-number.required' }),
                  },
                  {
                    pattern: /^\d{11}$/,
                    message: formatMessage({ id: 'validation.phone-number.wrong-format' }),
                  },
                ],
              })(
                <Input
                  size="large"
                  placeholder="请输入手机号"
                  onChange={this.getData}
                />
              )}
            </InputGroup>
          </FormItem>
          
          {
                this.state.checkName?
                (
                  <FormItem>
                  <div className={styles.userNameListCheck}  onClick={this.reset.bind(this)}>
                    <span className={styles.iconfix}><HeartIcon1 /></span>
                    <span className={styles.userName}>{this.state.checkName}</span> 
                    <span>{this.state.checkCName}</span>
                  </div>
                  </FormItem>):""
                
              }
          {
                this.state.getDataList && this.state.checkName==""  ?

                  ( <FormItem><div><span className={styles.checkCode}>
                    请选择要登录的账号
                  </span>
                    <div className={styles.userNameList}>
                      {
                        this.state.getDataList.map((item,index) => {
                          return <div className={styles.userNameListTag} key={item.username} onClick={this.checkUsername.bind(this,item.username,item.corporate)}>
                          <span className={styles.iconfix}><HeartIcon /><HeartIcon1 /></span><span className={styles.userName}>{item.username}</span> <span>{item.corporate}</span>
                        </div>
                        })
                      }
                      {/* <div className={styles.userNameListTag}>
                        <span className={styles.iconfix}><HeartIcon /><HeartIcon1 /></span><span className={styles.userName}>Cocoraty21294</span> <span>数据化登浩有限公司</span>
                      </div> */}
                    </div></div></FormItem>) : ""
              }
          
          <FormItem>
            <Row gutter={8}>
              <Col span={16}>
                {getFieldDecorator('verificationCode', {
                  rules: [
                    {
                      required: true,
                      message: formatMessage({ id: 'validation.verification-code.required' }),
                    },
                  ],
                })(
                  <Input
                    size="large"
                    onChange={this.getCode}
                    placeholder={formatMessage({ id: 'form.verification-code.placeholder' })}
                  />
                )}
              </Col>
              <Col span={8}>
                <Button
                  size="large"
                  disabled={count}
                  className={styles.getCaptcha}
                  onClick={this.onGetCaptcha}
                >
                  {count
                    ? `${count} s`
                    : formatMessage({ id: 'app.register.get-verification-code' })}
                </Button>
              </Col>
            </Row>
          </FormItem>
          <FormItem >
            <Popover
              getPopupContainer={node => node.parentNode}
              
              overlayStyle={{ width: 0 }}
              placement="right"
              visible={visible}
            >
              {getFieldDecorator('password', {
                rules: [
                  {
                    required: true,
                    message: formatMessage({ id: 'validation.confirm-password.required' }),
                  },
                  {
                    validator: this.checkPassword,
                  },
                  
                ],
                
              })(
                <Input
                  size="large"
                  type="password"
                  placeholder={formatMessage({ id: 'form.password.placeholder' })}
                />
              )}
            </Popover>
          </FormItem>
          <FormItem>
            {getFieldDecorator('confirm', {
              rules: [
                {
                  required: true,
                  message: formatMessage({ id: 'validation.confirm-password.required' }),
                },
                {
                  validator: this.checkConfirm,
                },

              ],
              
            })(
              <Input
                size="large"
                type="password"
                placeholder={formatMessage({ id: 'form.confirm-password.placeholder' })}
              />
            )}
          </FormItem>
         
          <FormItem>
            <Button
              size="large"
              loading={submitting}
              className={styles.submit}
              type="primary"
              htmlType="submit"
            >
              <FormattedMessage id="app.register.register" />
            </Button>
            {/* <Link className={styles.login} to="/auth/login">
              <FormattedMessage id="app.register.sing-in" />
            </Link> */}
          </FormItem>
           <Link className={styles.login} to="/auth/login">
              返回登录
            </Link>
        </Form>
      </div>
    );
  }
}

export default Register;
